package com.ai.deepseekspring.chatmemory;

import com.ai.deepseekspring.domain.dto.ChatMessageDo;
import com.ai.deepseekspring.mapper.ChatMessageMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;



public class MySQLChatMemory implements ChatMemory {



    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Override
    public void add(String conversationId, Message message) {
        ChatMessageDo chatMessageDo = new ChatMessageDo();
        chatMessageDo.setConversationId(conversationId);
        chatMessageDo.setRole(message.getMessageType().name());
        chatMessageDo.setContent(message.getText());
        chatMessageMapper.insert(chatMessageDo);
    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        messages.forEach(message -> add(conversationId, message));
    }


    @Override
    public List<Message> get(String conversationId) {
        LambdaQueryWrapper<ChatMessageDo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageDo::getConversationId, conversationId);

        return chatMessageMapper.selectList(queryWrapper)
                .stream()

                .map(e -> new UserMessage(e.getContent()))
                .collect(Collectors.toList());
    }

    @Override
    public void clear(String conversationId) {
        LambdaQueryWrapper<ChatMessageDo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageDo::getConversationId, conversationId);
        chatMessageMapper.delete(queryWrapper);

    }
}
